<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="submitForm"
    @cancel="handleCancel"
    destroyOnClose
    :maskClosable="false"
    :zIndex="10000"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="false">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-row :gutter="48">
            <a-col :span="24">
              <a-form-model-item label="流程定义id" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processId" v-if="false">
                <a-input v-model="model.processId" placeholder="请输入流程定义id"  ></a-input>
              </a-form-model-item>
            </a-col>
<!--            <a-col :span="24">
              <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processName">
                <j-popup
                  :multi="false"
                  disabled
                  v-model="model.processName"
                  field="processName"
                  org-fields="process_name,id"
                  dest-fields="processName,processId"
                  code="sys_process_report"
                  @input="popupCallback"
                  :showIt = false
                  />
              </a-form-model-item>
            </a-col>-->
            <!-- <a-col :span="24">
              <a-form-model-item label="应用部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDepart">
                <!~~ <a-input v-model="model.applyDepart" placeholder="请输入应用部门"  ></a-input> ~~>
                <j-select-depart placeholder="请选择应用部门" v-model="model.applyDepart" :multi="false" @change="getapplydepart" />
              </a-form-model-item>
            </a-col> -->
  <!--          <a-col :span="24">-->
  <!--            <a-form-model-item label="流程是否更新" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isUpdate">-->
  <!--              <j-dict-select-tag type="list" v-model="model.isUpdate" dictCode="YES_OR_NO" placeholder="请选择流程是否更新" />-->
  <!--            </a-form-model-item>-->
  <!--          </a-col>-->
          </a-row>
          <a-tabs defaultActiveKey="1" >
            <a-tab-pane tab="流程节点人员配置" key="1">
              <div>
                <a-row type="flex" style="margin-bottom:10px" :gutter="24">
                  <a-col :span="9">节点名称</a-col>
                  <a-col :span="14">操作人</a-col>
<!--                  <a-col :span="5">备注</a-col>-->
                </a-row>

                <a-row :gutter="24" v-for="(item, index) in model.erpProcessConfigMainVoList" :key="index">
                  <div v-if="item.taskType.includes('UserTask') || item.nodeName.includes('知会')" style="margin-bottom:20px">
                    <!-- <a-col :span="6">
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.id">
                        <a-input placeholder="id" v-model="item.id" />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="6" >
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.execDepart">
                        <j-select-depart placeholder="请选择执行部门" disabled v-model="item.execDepart" :multi="false"  />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="6">
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.processNodeCode">
                        <a-input placeholder="processNodeCode" v-model="item.processNodeCode" />
                      </a-form-model-item>
                    </a-col> -->
                    <a-col :span="9">
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.nodeName">
                        <!-- <j-dict-select-tag type="list" placeholder="节点名称"  v-decorator="[item.nodeId,{'initialValue':item.nodeId}]"   dictCode="ext_act_process_node,process_node_name,id"  /> -->
                        <!-- <j-dict-select-tag type="list" placeholder="节点名称" disabled   v-model="item.nodeId"   dictCode="ext_act_process_node,process_node_name,id"  /> -->
                        <a-input placeholder="节点名称" v-model="item.nodeName" disabled />
                      </a-form-model-item>
                    </a-col>
                    <template v-if="item.taskType.includes('ServiceTask')">
                      <a-col :span="14"  >
                        <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.execUser">
                          <!--                        <process-select-user v-model="item.execUser" disabled :multi="true"></process-select-user>-->
                          <a-input placeholder="执行人" v-model="item.nodeName" disabled />
                          <!--                        <process-select-user v-model="item.linUser" disabled :ids="item.execUser"></process-select-user>-->
                        </a-form-model-item>
                      </a-col>
                    </template>
                    <template v-else>
                      <a-col :span="14" v-if="item.isSelectDisabled === '0'">
                        <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.execUser">
                          <!--                        <process-select-user v-model="item.execUser" disabled :multi="true"></process-select-user>-->
                          <a-input placeholder="执行人" v-model="item.nodeName" disabled />
                          <!--                        <process-select-user v-model="item.linUser" disabled :ids="item.execUser"></process-select-user>-->
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="14" v-else>
                        <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.execUser">
                          <process-select-user v-model="item.linUser" :ids="item.execUser" :multi="item.isMultAssignee=='1'" :isSequenceApprove="item.isSequenceApprove=='1'"></process-select-user>
                        </a-form-model-item>
                      </a-col>
                    </template>
<!--                    <a-col :span="5"  v-if=" item.isSelectDisabled === '0'? true: ( item.isConfigExpression=='0' ||  item.nodeName.includes('知会') ? true :false) ">
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.remark">
                        <a-input placeholder="备注" value="当前节点无需配置" disabled />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="5" v-else>
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.remark">
                        <a-input placeholder="备注" v-model="item.remark" />
                      </a-form-model-item>
                    </a-col>-->
                  </div>
                </a-row>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-form-model>
      </j-form-container>
    </a-spin>
  </a-modal>
</template>

<script>

  import { getAction,postAction } from '@/api/manage'
  // import { validateDuplicateValue } from '@/utils/util'
  import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
  import ProcessSelectUser from '@/views/scy/components/ProcessSelectUser'
  // import pick from 'lodash.pick';
  // import moment from 'moment';
  export default {
    name: 'erpProcessConfigForm',
    components: {
      SelectPersonInput,
      ProcessSelectUser
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      isCheck: {
        type: String,
        default: "0",
        required: false
      },
      isAfterStart: {
        type: String,
        default: "0",
        required: false
      }
    },
    data () {
      return {
        model:{
          erpProcessConfigMainVoList: []
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {},
        url: {
          save: '/api/erp/process/erpProcessConfigData/addBatch',
          queryById: "/api/erp/base/getBpmListByCode",
          quertyProcessNodeListById: '/api/erp/process/erpProcessConfigMain/queryListByMainId',
          startProcess: "/api/erpmng/act/process/extActProcess/startMutilProcess"
        },
        title:"操作",
        width:"50%",
        visible: false,
        processId: '',
        recordData: {},
        flowCode: '',
        formUrl: '',
        formUrlMobile: ''
      }
    },
    // computed: {
    //   formDisabled(){
    //     return this.disabled
    //   },
    // },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      handleCancel () {
        this.$emit('close');
        this.visible = false;
      },
      // getapplydepart(value){
      //   this.model.erpProcessConfigMainVoList.forEach(val => {
      //     val.execDepart = value
      //   })
      // },
      edit (record, processId, beanName) {
        this.$nextTick(() => {
          this.$refs.form.resetFields();
        })
        this.processId = processId
        this.beanName = beanName
        this.recordData = record
        this.model.erpProcessConfigMainVoList = [];
        //初始化明细表数据
        let params = {
          id: record.id,
          beanName: beanName,
          flowCode: this.flowCode
        }
        console.log(params)
        // //初始化流程配置详情
        getAction(this.url.queryById,params).then((res)=>{
          console.log(res);
          if (res.success) {
            console.log(res);
            res.result.map(v => v.linUser = v.execUser)
            this.$set(this.model,'erpProcessConfigMainVoList',res.result)
            this.$forceUpdate()
            this.visible = true;
          } else {
            this.$message.warning(res.message);
            this.visible = false;
            this.$emit('close');
          }
        })
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            // let value = that.model.erpProcessConfigMainVoList.filter(val => !val.execUser || !val.nodeId)
            // let value = that.model.erpProcessConfigMainVoList.filter(val => !val.nodeId)
            // console.log(value);
            // if(value.length > 0){
            //   this.$message.warning('请选择执行人或节点')
            //   that.confirmLoading = false;
            //   return
            // }
            let flag = false
            let flag1 = false
            var warnMessage = ''
            this.model.erpProcessConfigMainVoList.forEach(val => {
              warnMessage = ''
              val.dataId = this.recordData.id
              // debugger;
              var flowPrifex = this.flowCode.slice(0,this.flowCode.indexOf('_'));
              if (flowPrifex === 'onl') {
                val.dataTable = this.flowCode.slice(this.flowCode.indexOf('_') + 1,this.flowCode.length)
              } else if (flowPrifex === 'dev') {
                val.dataTable = this.flowCode.slice(this.flowCode.indexOf('_') + 1,this.flowCode.lastIndexOf('_'))
              }
              console.log('val' , val)
              if (val.taskType.includes('UserTask')  && val.isSelectDisabled !== '0') {
                  if (!val.linUser) {
                    flag = true
                    return
                  }

                  if(val.linUser.split(',').length !== 1 && !val.nodeName.includes('知会') && val.isSelectDisabled !== '0' && val.isMultAssignee !== '1') {
                    console.log('val.nodeName', val.nodeName)
                    console.log(val)
                    console.log(val.linUser.split(',').length)
                    flag1 = true
                    this.$message.warning("【"+val.nodeName+'】只能选择一个审批人')
                    that.confirmLoading = false;
                    return
                  }
              }
            })
            if (flag) {
              this.$message.warning('请完善执行人')
              that.confirmLoading = false;
              return
            }
            if (flag1) {
                return
              }
            this.model.erpProcessConfigMainVoList.map(v => v.execUser = v.linUser)
            const params = {
              dataList: Object.assign([],this.model.erpProcessConfigMainVoList),
              id: this.recordData.id
            }
            postAction(that.url.save,params).then((res)=>{
              if(res.success) {
                var param = {
                  flowCode: that.flowCode,
                  id: that.recordData.id,
                  formUrl: that.formUrl,
                  formUrlMobile: that.formUrlMobile,
                  beanName: that.beanName,
                  isCheck: that.isCheck,
                  isAfterStart: that.isAfterStart
                }
                postAction(that.url.startProcess, param).then((res) => {
                  if (res.success) {
                    that.$message.success(res.message);
                    that.$emit('ok')
                  } else {
                    that.$message.warning(res.message);
                    this.$emit('close');
                  }
                }).catch((e) => {
                  this.$message.warning('不识别的请求!');
                  this.$emit('close');
                }).finally(() => {
                  that.confirmLoading = false;
                  that.visible = false;
                })
              } else {
                that.$message.warning(res.message);
              }
            }).catch(err=>{

              this.$message.error(err)
            })
          }
        })
      },
      popupCallback(value,row,obj){
        this.model.erpProcessConfigMainVoList = [];
        this.$set(this.model,'processId',obj.id)
        this.$set(this.model,'processName',obj.process_name)
        // 查询要业务信息档案
        this.ListData(this.model.id,this.processId)
      },
      ListData(mainId,processId){
        getAction(this.url.quertyProcessNodeListById, { mainId ,processId }).then(res => {
          if(res.success){
            console.log(res);
            // res.result.forEach((item) => {
              // if(this.model.applyDepart){
              //   data.push({ nodeId: item.id, nodeName: item.processNodeName,processNodeCode: item.processNodeCode,execDepart: this.model.applyDepart,taskType: item.taskType,isMultAssignee: item.isMultAssignee,isConfigExpression: item.isConfigExpression })
              // } else {
              //   data.push({ nodeId: item.id, nodeName: item.processNodeName,processNodeCode: item.processNodeCode,taskType: item.taskType,isMultAssignee: item.isMultAssignee,isConfigExpression: item.isConfigExpression })
              // }
            // })
            res.result.map(v => v.linUser = v.execUser)
            this.$set(this.model,'erpProcessConfigMainVoList',res.result)
            this.$forceUpdate()
          }
        })
      }
    }
  }
</script>
